import router from '@/router'
import { hasPermiOr, hasRoleOr } from '@/utils/auth'
import { buildMenus, filterAsyncRouter } from '@/plugins/menu'
import { constantRoutes, dynamicRoutes } from '@/router/routers'
import { getRoutersApi } from '@/api/login'

const usePermissionStore = defineStore('permission', {
  state: () => ({
    routes: [],
    addRoutes: [],
    defaultRoutes: [],
    topbarRouters: [],
    sidebarRouters: []
  }),
  actions: {
    setRoutes(routes) {
      this.addRoutes = routes
      this.routes = constantRoutes.concat(routes)
    },
    setDefaultRoutes(routes) {
      this.defaultRoutes = constantRoutes.concat(routes)
    },
    setTopbarRoutes(routes) {
      this.topbarRouters = routes
    },
    setSidebarRouters(routes) {
      this.sidebarRouters = routes
    },
    generateRoutes() {
      return new Promise(resolve => {
        // 向后端请求路由数据
        getRoutersApi().then(res => {
          const menuTreeList = buildMenus(res.list)
          const sdata = JSON.parse(JSON.stringify(menuTreeList))
          const rdata = JSON.parse(JSON.stringify(menuTreeList))
          const defaultData = JSON.parse(JSON.stringify(menuTreeList))
          const sidebarRoutes = filterAsyncRouter(sdata)
          const rewriteRoutes = filterAsyncRouter(rdata, false, true)
          const defaultRoutes = filterAsyncRouter(defaultData)
          const asyncRoutes = filterDynamicRoutes(dynamicRoutes)
          // rewriteRoutes.push({ path: '*', redirect: '/404', hidden: true })
          asyncRoutes.forEach(route => router.addRoute(route))
          this.setRoutes(rewriteRoutes)
          this.setSidebarRouters(constantRoutes.concat(sidebarRoutes))
          this.setDefaultRoutes(sidebarRoutes)
          this.setTopbarRoutes(defaultRoutes)
          resolve(rewriteRoutes)
        })
      })
    }
  }
})

// 动态路由遍历，验证是否具备权限
export function filterDynamicRoutes(routes) {
  const res = []
  routes.forEach(route => {
    if (route.permissions) {
      if (hasPermiOr(route.permissions)) {
        res.push(route)
      }
    } else if (route.roles) {
      if (hasRoleOr(route.roles)) {
        res.push(route)
      }
    }
  })
  return res
}

export default usePermissionStore
